<script setup lang="ts">
import { Login } from '@/apis/login'
import router from '@/router'
import { setLocalToken } from '@/utils/auth'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

import { ref } from 'vue'

// 表单数据类型
interface LoginParams {
  mobile: string
  code: string
  agree: boolean
}
// 表单数据
const formData = ref<LoginParams>({
  mobile: '13200000000',
  code: '246810',
  agree: false,
})

//自定义校验

// 表单校验规则
const formRules = ref<FormRules<LoginParams>>({
  mobile: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur',
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur',
    },
    {
      min: 6,
      message: '请输入至少6位数的验证码',
      trigger: 'blur',
    },
  ],
  agree: [
    {
      required: true,
      message: '请勾选「用户协议」和「隐私条款」',
      trigger: 'blur',
    },
  ],
})

// 登录业务
const loginFormRef = ref<FormInstance>()
const onLogin = () => {
  loginFormRef.value?.validate(async (res) => {
    if (res) {
      // 校验通过发送请求
      const res = await Login(formData.value)
      console.log(res)
      if (res.message === 'OK') {
        // 获取token
        setLocalToken(res.data.token)
        // 跳转到登录页
        router.push('/article')
        // 提示消息
        ElMessage.success('登陆成功！')
      } else {
        ElMessage.warning(res.message)
      }
    } else {
    }
  })
}
//
</script>
<template>
  <div class="container">
    <el-card>
      <img class="logo" src="../../assets//images/logo.png" />
      <el-form :model="formData" :rules="formRules" ref="loginFormRef">
        <el-form-item prop="mobile">
          <el-input placeholder="请输入手机号" v-model="formData.mobile"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input placeholder="请输入验证码" v-model="formData.code"></el-input>
        </el-form-item>
        <el-form-item prop="agree">
          <el-checkbox v-model="formData.agree"
            >我已阅读并同意「用户协议」和「隐私条款」</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin()">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<style scoped lang="less">
.container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url(@/assets/images/login.png);
  .el-card {
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);
    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }
  }
}
</style>
